package com.oracle.controller;

import com.oracle.comment.Constants;
import com.oracle.pojo.Role;
import com.oracle.pojo.User;
import com.oracle.service.RoleService;
import com.oracle.service.UserService;
import com.oracle.utils.HttpUtils;
import com.oracle.utils.R;
import org.apache.http.HttpResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
@Controller
public class UserController extends  BaseController{
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @RequestMapping(value = "login",method = RequestMethod.GET)
    public String login(){
        return "login";
    }
    @RequestMapping(value = "reg",method = RequestMethod.GET)
    public String reg(){
        return "reg";
    }
    @RequestMapping(value = "index",method = RequestMethod.GET)
    public String index() {
        return "index";
    }
    @RequestMapping(value = "adminIndex",method = RequestMethod.GET)
    public String adminIndex() {
        return "admin/index";
    }

    @RequestMapping(value="/sendPhoneCode",method = RequestMethod.POST)
    @ResponseBody
    public R sendPhoneCode(String phone, HttpSession session) {

        String host = "http://dingxin.market.alicloudapi.com";
        String path = "/dx/sendSms";
        String method = "POST";
        String appcode = "291f90cbc4414a7e8b719cbd608a5333";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", phone);
        Random r = new Random();
        int code = r.nextInt(100000);
        session.setAttribute("SMS_CODE",code);
        querys.put("param", "code:" + code);
        querys.put("tpl_id", "TP1711063");
        Map<String, String> bodys = new HashMap<String, String>();
        System.out.println("code"+code);
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
        }catch (Exception e){
            e.printStackTrace();
            return R.error("短信发送失败");
        }

        return R.ok("短信发送成功");
    }

    @RequestMapping(value="/regUser",method = RequestMethod.POST)
    @ResponseBody
    public R regUser(String code,HttpSession session,String phone,String passWord) {
        String smsCode = session.getAttribute("SMS_CODE")+"";
        if(code.equals(smsCode)){
            SimpleHash sh = new SimpleHash("MD5", passWord, smsCode, 1024);
            User user=new User();
            user.setPhone(phone);
            user.setPassWord(sh.toString());
            user.setSalt(smsCode);
            userService.save(user);
            return R.ok("注册成功");
        }else{
            return R.error("校验失败");
        }
    }


    @RequestMapping("/loginIn")
    @ResponseBody
    public R login(User user) {

        // 创建Subject实例
        Subject subject = SecurityUtils.getSubject();
        // 判断当前用户是否登陆
        if (subject.isAuthenticated() == false) {
            UsernamePasswordToken token = new UsernamePasswordToken(user.getPhone(), user.getPassWord());
            try {
                subject.login(token);
                Session session = getSession();
                user = (User) session.getAttribute(Constants.CURRENT_USER);
                session.setAttribute("SESSION_USERNAME", user.getId() + "");
            } catch (Exception e) {
                // 这里将异常打印关闭是因为如果登录失败的话会自动抛异常
                e.printStackTrace();
                return R.error();
            }
        } else {
            Session session = getSession();
            user = (User) session.getAttribute(Constants.CURRENT_USER);
            session.setAttribute("SESSION_USERNAME", user.getId() + "");
        }
        List<Role> roleList = roleService.findRolesByUserID(user.getId());
        Session session = getSession();
        session.setAttribute("roleList",roleList);
        String temp = "";
        for(Role role:roleList){
            if(role.getRoleCode().equals("admin")){
                temp="admin";
            }
        }
        return R.ok(temp);
    }
}
